#========================================
# author: changlong.zang
#   mail: zclongpop@163.com
#   date: Wed, 05 Aug 2015, 15:34:50
#========================================
import sys, os, re
import scriptTool, maya.OpenMayaUI
try:
    from PyQt4 import QtCore, QtGui, uic
    import sip
    USE_PYQT_MODULE = True

except:
    from PySide import QtCore, QtGui
    import cStringIO, xml.etree.ElementTree, shiboken, pysideuic
    USE_PYQT_MODULE = False
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
sys.path.append(os.path.join(scriptTool.getResourcePath(), 'Qt'))

def wrapInstance(widget):
    '''
    Convert maya UI object to Qt object...
    '''
    if isinstance(widget, basestring):
        widget = maya.OpenMayaUI.MQtUtil.findWindow(widget)

    if USE_PYQT_MODULE:
        return sip.wrapinstance(long(widget), QtCore.QObject)
    else:
        return shiboken.wrapInstance(long(widget), QtGui.QWidget)



def getMayaWindow():
    '''
    return maya window by Qt object..
    '''
    maya_window = maya.OpenMayaUI.MQtUtil.mainWindow()
    return wrapInstance(maya_window)



def loadUi(uiPath):
    '''
    read an ui file, get two classes to return..
    '''
    if USE_PYQT_MODULE:
        form_class, base_class = __pyqtLoadUi(uiPath)
    else:
        form_class, base_class = __pysideLoadUi(uiPath)
    return form_class, base_class




def __pyqtLoadUi(uiPath):
    '''
    read an ui file, use PyQt4 method get two classes to return..
    '''
    return uic.loadUiType(uiPath)



def __pysideLoadUi(uiPath):
    '''
    read an ui file, use PySide method get two classes to return..
    '''
    parsed = xml.etree.ElementTree.parse(uiPath)
    widget_class = parsed.find('widget').get('class')
    form_class = parsed.find('class').text

    with open(uiPath, 'r') as f:
        o = cStringIO.StringIO()
        frame = dict()

        pysideuic.compileUi(f, o, indent=0)
        pyc = compile(o.getvalue(), '<string>', 'exec')
        exec pyc in frame

        form_class = frame['Ui_%s'%form_class]
        base_class = eval('QtGui.%s'%widget_class)

    return form_class, base_class



def connectPySideSignals(instance):
    '''
    '''
    if USE_PYQT_MODULE:
        return

    for cls in scriptTool.getParentClasses(instance):
        for fn in cls.__dict__:
            if not re.match('on_', fn):
                continue

            control_name = fn.split('_', 1)[-1].rsplit('_', 1)[0]
            signal_name  = fn.rsplit('_', 1)[-1]

            control = getattr(instance, control_name)
            signal  = getattr(control, signal_name)
            slot    = getattr(instance, fn)

            signal.connect(slot)





def windowExists(name):
    '''
    get named window, if window exists, return true; if not, return false..
    '''
    widget = maya.OpenMayaUI.MQtUtil.findWindow(name)
    if not widget:
        return False

    wnd = wrapInstance(widget)
    wnd.showNormal()
    wnd.activateWindow()

    return True



def ui_initialize_wraper(object_name):
    '''
    '''
    def wraper(func):
        def initalize(*args, **kargs):
            if windowExists(object_name):
                return
            func(*args, **kargs)

        wraper.__name__ = func.__name__
        wraper.__doc__ = func.__doc__

        return initalize

    return wraper




def getChildrenWindows(parent):
    '''
    get object's children windows..
    '''
    if not parent:return

    for child in parent.children():
        if not hasattr(child, 'isWindow'):
            continue

        if not child.isWindow():
            continue

        yield child
